<template>
  <div ref="chart" style="width: 100%; height: 100%;"></div>
</template>

<script>
import * as echarts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'
import MapCenterClick from '@/mixins/map-center-click'

const erd = elementResizeDetectorMaker()
function geoJSON (mapCode, isFull) {
  return fetch(`https://geo.datav.aliyun.com/areas_v3/bound/${mapCode}${isFull ? '_full' : ''}.json`)
    .then(res => res.json())
    .then(data => data)
}

export default {
  name: 'map-center',
  mixins: [MapCenterClick],
  props: {
    map: {
      type: String,
      default: '360100'
    },
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    },
    enterpriseList () {
      return this.$store.state.energyEnterpriseList
    },
  },
  data () {
    return {
      chart: null,
      json1: null,
      json2: null,
      option: {},
    }
  },
  watch: {
    enterpriseList: {
      deep: true,
      handler () {
        this.initScatter()
      },
    }
  },
  async mounted () {
    this.$store.dispatch('GET_ENTERPRISE_LIST')

    const mapCode = this.map
    const json1 = this.json1 = await geoJSON(mapCode)
    const json2 = this.json2 = await geoJSON(mapCode, true)
    echarts.registerMap(mapCode, json1)
    echarts.registerMap(mapCode + '_full', json2)
    const chart = this.chart = echarts.init(this.$refs.chart)
    const option = this.option = this.getChartOption()
    chart.setOption(option)

    setTimeout(() => {
      this.initScatter()
    }, 200)
    erd.listenTo(this.$refs.chart, function () {
      chart.resize({
        animation: {
          duration: 1000,
        }
      })
    })
  },
  beforeDestroy () {
    erd.removeAllListeners(this.$refs.chart)
  },
  methods: {
    getChartOption () {
      const vm = this
      const getData = this.getData
      const toHTML = this.toHTML
      const regions = this.json2.features
      const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
      return {
        tooltip: {
          trigger: 'item',
          position: function (point) {
            const [x, y] = point
            return [x + 20, y - 20]
          },
        },
        geo: [
          {
            map: this.map,
            left: '2%',
            right: '2%',
            top: '2%',
            bottom: '2%',
            itemStyle: {
              areaColor: 'transparent',
              borderColor: '#50fdfc',
              borderWidth: 0,
            },
            emphasis: {
              disabled: true,
            },
            tooltip: {
              show: false,
            },
          },
          {
            map: this.map + '_full',
            left: '2%',
            right: '2%',
            top: '2%',
            bottom: '2%',
            itemStyle: {
              borderColor: colors[2],
            },
            regions: [
              ...regions.map((v, i) => ({
                adcode: v.properties.adcode,
                name: v.properties.name,
                label: {
                  show: true,
                  color: '#ffffff',
                },
                itemStyle: {
                  areaColor: colors[i],
                  opacity: 0.6
                },
                emphasis: {
                  itemStyle: {
                    areaColor: colors[i],
                    opacity: 1
                  }
                },
                tooltip: {
                  show: false,
                  formatter: function (params, ticket, callback) {
                    if (vm.regionName !== params.name) {
                      vm.regionHTML = '<div style="min-height: 150px;">loading...</div>'
                      getData().then(res => {
                        // TODO
                        const data = [params.name, ...res]
                        vm.regionName = params.name
                        const regionHTML = vm.regionHTML = toHTML(data)
                        callback(ticket, regionHTML)
                      })
                    }
                    return vm.regionHTML
                  },
                  backgroundColor: 'rgba(12,27,88,0.9)',
                  extraCssText: `
                    width: 400px;
                    color: #ccc;
                    border-radius: 6px;
                    box-shadow: 0 4px 10px rgba(0,0,0,0.2);
                  `
                },
              }))
            ],
          },
        ],
      }
    },
    getData (name) {
      return new Promise((resolve) => {
        const rand = () => Math.round(Math.random() * 1000)
        setTimeout(() => {
          resolve(Array(8).fill(1).map(v => rand()))
        }, 400)
      })
    },
    toHTML (data) {
      const [v1, v2, v3, v4, v5, v6, v7, v8, v9] = data
      return `
        <table class="tooltip-table">
          <caption style="line-height: 2;">${v1}（${v2}家企业）</caption>
          <thead>
            <tr>
              <td>名称</td>
              <td>数值</td>
              <td>单位</td>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>综合能源消费量</td>
              <td>${v3}</td>
              <td>万吨标准煤</td>
            </tr>
            <tr>
              <td>用电量</td>
              <td>${v4}</td>
              <td>万吨标准煤</td>
            </tr>
            <tr>
              <td>用煤量</td>
              <td>${v5}</td>
              <td>万吨标准煤</td>
            </tr>
            <tr>
              <td>万元工业总产值工业消耗</td>
              <td>${v6}</td>
              <td>千克标准煤/万元</td>
            </tr>
            <tr>
              <td>工业总产值</td>
              <td>${v7}</td>
              <td>万元</td>
            </tr>
            <tr>
              <td>工业增加值</td>
              <td>${v8}</td>
              <td>万吨标准煤</td>
            </tr>
            <tr>
              <td>万元工业增加值综合消耗</td>
              <td>${v9}</td>
              <td>千克标准煤/万元</td>
            </tr>
          </tbody>
        </table>
      `
    },
    update (option = {}) {
      if (this.chart) {
        this.chart.setOption({
          ...this.chartOption,
          ...option
        })
      }
    },
    initScatter () {
      const data = this.enterpriseList
      const chart = this.chart
      const option = this.option = {
        ...this.option,
        series: [
          {
            zlevel: 21,
            type: 'effectScatter',
            coordinateSystem: 'geo',
            rippleEffect: {
              number: 3,
              period: 5,
              scale: 10,
              brushType: 'stroke',
            },
            symbolSize: 5,
            itemStyle: {
              color: '#50fdfc'
            },
            label: {
              show: false,
              color: 'red',
              formatter: '{@[2]}',
            },
            emphasis: {
              label: {
                show: true,
              },
            },
            data: [
              ...data.map((v, i) => ({
                name: v.districtBelongName,
                value: [
                  v.longitude,
                  v.latitude,
                ],
              }))
            ]
          },
        ],
      }
      chart.setOption(option)
    },
  }
}
</script>
